<template>
  <el-select
    v-model="selectValue"
    :loading="props.loading"
    :placeholder="props.placeholder"
  >
    <el-option label="|--（无）" :value="0"></el-option>
    <template v-for="item in renderParentOptions" :key="item.id">
      <el-option :label="item.title" :value="item.id">
        |--
        <span>{{ item.title }}</span>
      </el-option>
      <template v-if="item.children">
        <el-option
          v-for="_item in item.children"
          :key="_item.id"
          :label="_item.title"
          :value="_item.id"
        >
          |----
          <span>{{ _item.title }}</span>
        </el-option>
      </template>
    </template>
  </el-select>
</template>

<script setup lang="ts">
import { computed, PropType } from 'vue';
import * as _ from 'lodash';

const props = defineProps({
  modelValue: {
    type: [Number, String],
    required: true,
    default: ''
  },

  // 起始节点的ID
  rootId: {
    type: Number,
    default: 0
  },

  options: {
    type: Array as PropType<any[]>,
    required: true,
    default: []
  },

  loading: {
    type: Boolean,
    default: false
  },

  placeholder: {
    type: [String, Number],
    default: ''
  }
});

// emits
const emits = defineEmits(['update:modelValue']);

const selectValue = computed({
  get: () => props.modelValue,
  set: (val) => {
    emits('update:modelValue', val);
  }
});

// 计算 - 过滤自己
const renderParentOptions = computed(() => {
  if (!props.rootId) return props.options;

  // 深拷贝
  const data = _.cloneDeep(props.options);
  fillterTreeById(props.rootId, data);
  return data;
});

// 深度过滤相同id的tree
const fillterTreeById = (id: number, data?: any[]) => {
  if (!data) return;
  for (let i = 0; i < data.length; i++) {
    const item = data[i];
    if (item.id == id) {
      data.splice(i, 1);
      break;
    }
    if (item.children) {
      fillterTreeById(id, item.children);
    }
  }
};
</script>

<style lang="scss" scoped></style>
